/*
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: WithdrawCoinPresenter.java
 *   @Date: 18-11-29 下午4:05
 *   @Author: ppzhao
 *   @Description:
 *   @Copyright（C）: 2018 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 */

package io.bhex.app.account.presenter;

import android.text.TextUtils;

import java.util.List;

import io.bhex.app.R;
import io.bhex.app.base.AppUI;
import io.bhex.app.utils.NetWorkStatus;
import io.bhex.baselib.network.response.UISafeKeeper;
import io.bhex.sdk.account.LoginApi;
import io.bhex.sdk.account.UserInfo;
import io.bhex.sdk.account.bean.UserInfoBean;
import io.bhex.sdk.trade.AssetApi;
import io.bhex.sdk.trade.bean.AddressCheckResponse;
import io.bhex.sdk.trade.bean.AddressListResponse;
import io.bhex.sdk.trade.bean.CodeOrderIdBean;
import io.bhex.sdk.trade.bean.FeeBeanResponse;
import io.bhex.sdk.trade.bean.VerifyWithDrawRequest;
import io.bhex.sdk.trade.bean.WithDrawRequstBean;
import io.bhex.sdk.trade.bean.WithDrawVerifyBean;
import io.bhex.sdk.trade.bean.WithdrawCreateRequest;
import io.bhex.baselib.mvp.BaseCoreActivity;
import io.bhex.baselib.mvp.BasePresenter;
import io.bhex.baselib.network.Utils.CodeUtils;
import io.bhex.baselib.network.listener.SimpleResponseListener;
import io.bhex.baselib.utils.MD5Utils;
import io.bhex.baselib.utils.ToastUtils;

public class WithdrawCoinPresenter extends BasePresenter<WithdrawCoinPresenter.WithdrawCoinUI> {

    private FeeBeanResponse currentFeeBean;
    private List<AddressListResponse.AddressBean> currentAddressList;

    public interface WithdrawCoinUI extends AppUI {
        void showFeeInfo(FeeBeanResponse response);

//        void showBrokeVerify(WithDrawRequstBean response);

        void requestUserInfoSuccess(UserInfoBean data);

        void requestVerifyCodeSuccess(String codeOrderId);

        void showWithdrawSuccess();

        void showWithDrawFirst(WithDrawRequstBean response);

        void showWithDrawSecond(WithDrawVerifyBean response);

        void showFinancePasswd(boolean isShow);

        void showIdCard(boolean isShow);

        void showCheckAddress(boolean isGoWithDraw, AddressCheckResponse response);
    }

    @Override
    public void onUIReady(BaseCoreActivity activity, WithdrawCoinUI ui) {
        super.onUIReady(activity, ui);
    }

    public void resetData() {
//        currentFeeBean = null;
        currentAddressList = null;
    }

    /**
     * 获取手续费
     *
     * @param token
     * @param selectChainType
     */
    public void getQuotaInfo(String token, String selectChainType) {
        AssetApi.RequestQuotaInfo(token,selectChainType, new SimpleResponseListener<FeeBeanResponse>() {
            @Override
            public void onBefore() {
                super.onBefore();
                getUI().showProgressDialog("","");
            }

            @Override
            public void onFinish() {
                super.onFinish();
                getUI().dismissProgressDialog();
            }

            @Override
            public void onSuccess(FeeBeanResponse response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response, true)) {
                    currentFeeBean = response;
                    getUI().showFeeInfo(response);
                }
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
            }
        });
    }

    /**
     * 获取报价Token的地址集合
     * @param tokenId
     */
    public void getAddressListByToken(String tokenId,String chainType) {
        if (!NetWorkStatus.isConnected(getActivity())) {
            ToastUtils.showShort(getActivity(), getResources().getString(R.string.hint_network_not_connect));
            return;
        }

        AssetApi.RequestAddressListByToken(tokenId, chainType,UISafeKeeper.guard(getUI(), new SimpleResponseListener<AddressListResponse>() {
            @Override
            public void onFinish() {
                super.onFinish();
            }

            @Override
            public void onSuccess(AddressListResponse response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response, true)) {
                    currentAddressList = response.getArray();
                }
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
            }
        }));
    }

    /**
     * 判断是否在已地址列表里
     * @param address
     * @param tag
     * @param currentFeeBean
     * @return
     */
    public boolean isAddressList(String address, String tag, FeeBeanResponse currentFeeBean){
        boolean isAddressed = false;
        boolean isNeedAddressTag = false;
        if (currentFeeBean != null) {
            isNeedAddressTag = currentFeeBean.isNeedAddressTag();
        }

        if (currentAddressList != null) {
            for (AddressListResponse.AddressBean addressBean : currentAddressList) {
                String addressOfList="";
                String tagOfList="";
                if (!TextUtils.isEmpty(addressBean.getAddress())) {
                    addressOfList = addressBean.getAddress();
                }
                if (!TextUtils.isEmpty(addressBean.getAddressExt())) {
                    tagOfList = addressBean.getAddressExt();
                }

                if (isNeedAddressTag) {
                    if (address.equals(addressOfList)&&tag.equals(tagOfList)){
                        isAddressed = true;
                        break;
                    }
                }else{
                    if (address.equals(addressOfList)){
                        isAddressed = true;
                        break;
                    }
                }

            }
        }
        return isAddressed;
    }


    public AddressListResponse.AddressBean getAddressList(String address, String tag, FeeBeanResponse currentFeeBean) {
        AddressListResponse.AddressBean addressBeanOfList = null;
        boolean isNeedAddressTag = false;
        if (currentFeeBean != null) {
            isNeedAddressTag = currentFeeBean.isNeedAddressTag();
        }

        if (currentAddressList != null) {
            for (AddressListResponse.AddressBean addressBean : currentAddressList) {
                String addressOfList="";
                String tagOfList="";
                if (!TextUtils.isEmpty(addressBean.getAddress())) {
                    addressOfList = addressBean.getAddress();
                }
                if (!TextUtils.isEmpty(addressBean.getAddressExt())) {
                    tagOfList = addressBean.getAddressExt();
                }

                if (isNeedAddressTag) {
                    if (address.equals(addressOfList)&&tag.equals(tagOfList)){
                        addressBeanOfList = addressBean;
                        break;
                    }
                }else{
                    if (address.equals(addressOfList)){
                        addressBeanOfList = addressBean;
                        break;
                    }
                }

            }
        }
        return addressBeanOfList;
    }


    public void checkAddressIsInBlackList(final boolean isGoWithDraw, String tokenId,String chainType, String address, String tag) {
        AssetApi.checkAddress(tokenId,chainType,address,tag,new SimpleResponseListener<AddressCheckResponse>(){
            @Override
            public void onBefore() {
                super.onBefore();
//                getUI().showProgressDialog("","");
            }

            @Override
            public void onFinish() {
                super.onFinish();
//                getUI().dismissProgressDialog();
            }

            @Override
            public void onSuccess(AddressCheckResponse response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response,true)) {
                    getUI().showCheckAddress(isGoWithDraw,response);
                }
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
            }
        });
    }

    /**
     * 发起提币请求
     * @param token
     * @param address
     * @param amount
     * @param minerFee
     * @param authType
     * @param orderId
     * @param verifyCode
     * @param isNeedTag
     * @param tag
     * @param tradePasswd
     */
    public void requstWithdraw(final boolean isNeedHideFinancePasswdView, String token,String chainType, String address, String addressId, String amount, String minerFee, int authType, String orderId, String verifyCode, boolean isNeedTag, String tag, String tradePasswd ) {
        WithdrawCreateRequest requestData = new WithdrawCreateRequest();
        requestData.token = token;
        requestData.address = address;
        requestData.addressId = addressId;
        requestData.amount = amount;
        requestData.minerFee = minerFee;
        requestData.authType = authType;
        requestData.orderId = orderId;
        requestData.verifyCode = verifyCode;
        requestData.isNeedTag = isNeedTag;
        requestData.tag = tag;
        requestData.tradePasswd = MD5Utils.encode(tradePasswd);
        requestData.convertRate = currentFeeBean!=null?currentFeeBean.getConvertRate():"";
        requestData.chainType= chainType;

        AssetApi.RequstWithdrawCreate(requestData, new SimpleResponseListener<WithDrawRequstBean>() {
            @Override
            public void onBefore() {
                super.onBefore();
                getUI().showProgressDialog("","");
            }

            @Override
            public void onFinish() {
                super.onFinish();
                getUI().dismissProgressDialog();
            }

            @Override
            public void onSuccess(WithDrawRequstBean response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response, true)) {
//                    verifyWithdraw(response,"888888");
                    if (isNeedHideFinancePasswdView) {
                        getUI().showFinancePasswd(false);
                    }
                    getUI().showWithDrawFirst(response);
                }
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
                ToastUtils.showShort(getResources().getString(R.string.string_net_exception));
            }
        });
    }

    /**
     * 验证请求
     * @param isShowIdCardCheck
     * @param requestId
     * @param code
     * @param isSkipIdCard
     * @param idcardno
     */
    public void verifyWithdraw(final boolean isShowIdCardCheck, String requestId, String currentCodeId, String tokenId, String code, boolean isSkipIdCard, String idcardno) {
        final VerifyWithDrawRequest requestData = new VerifyWithDrawRequest();
        requestData.isShowIdCardCheck = isShowIdCardCheck;
        requestData.requestId = requestId;
        requestData.currentCodeId = currentCodeId;
        requestData.tokenId = tokenId;
        requestData.code = code;
        requestData.isSkip = isSkipIdCard;
        requestData.idcard = idcardno;
        AssetApi.RequestVerifyWithdraw(requestData, new SimpleResponseListener<WithDrawVerifyBean>() {
            @Override
            public void onBefore() {
                super.onBefore();
                getUI().showProgressDialog("","");
            }

            @Override
            public void onFinish() {
                super.onFinish();
                getUI().dismissProgressDialog();
            }

            @Override
            public void onSuccess(WithDrawVerifyBean response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response, true)) {
                    if (isShowIdCardCheck) {
                        getUI().showIdCard(false);
                    }
                    getUI().showWithDrawSecond(response);
                }
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
            }
        });
    }

    public void getUserInfo() {
        LoginApi.GetUserInfo(new SimpleResponseListener<UserInfoBean>(){

            @Override
            public void onBefore() {
                super.onBefore();
                getUI().showProgressDialog("","");
            }

            @Override
            public void onFinish() {
                super.onFinish();
                getUI().dismissProgressDialog();
            }

            @Override
            public void onSuccess(UserInfoBean data) {
                super.onSuccess(data);
                if (CodeUtils.isSuccess(data,true)) {
                    //保存用户数据
                    UserInfo.saveUserInfo(data);
                    getUI().requestUserInfoSuccess(data);
                }
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
            }
        });
    }

    /**
     * 获取资产托管平台验证码
     * @param requestId
     */
    public void requstBrokerVerifyCode(String requestId) {
        AssetApi.RequstBrokerVerifyCode(requestId,new SimpleResponseListener<CodeOrderIdBean>(){
            @Override
            public void onBefore() {
                super.onBefore();
                getUI().showProgressDialog("","");
            }

            @Override
            public void onFinish() {
                super.onFinish();
                getUI().dismissProgressDialog();
            }
            @Override
            public void onSuccess(CodeOrderIdBean data) {
                super.onSuccess(data);
                if (CodeUtils.isSuccess(data,true)) {
                    getUI().requestVerifyCodeSuccess(data.getCodeOrderId());
                }
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
                ToastUtils.showShort(getActivity(), getString(R.string.string_get_verify_code_failed));
            }
        });
    }
}
